/**
 * Author by justwen, Email 2422142078@qq.com, Date on 2021/3/12.
 * PS: Not easy to write code, please indicate.
 */
package com.example.myapp.Activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.ADO.MyDialog;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Article;
import com.example.myapp.Model.Defaulticon;
import com.example.myapp.Model.MyData;
import com.example.myapp.Model.User;
import com.example.myapp.R;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.QueryListener;

public class Login extends AppCompatActivity {
    private  EditText login_phone;
    private  EditText login_pwd;
    private  Button login_reg;
    private  Button login_forget;
    private  Button login_go;
    private    BmobFile neticon;
    private  MyData myData;
    private  ShapeLoadingDialog shapeLoadingDialog;








    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.login);
        judgePermission();
      ImageView login_back = findViewById(R.id.login_back);
        login_phone = findViewById(R.id.login_phone);
        login_pwd = findViewById(R.id.login_pwd);
        login_reg = findViewById(R.id.login_reg);
        login_forget = findViewById(R.id.login_forget);
        login_go = findViewById(R.id.login_go);
        myData = (MyData) getApplication();


        login_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //记住密码准备
        SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        if (sp.getBoolean("save", false) == true) {
            login_phone.setText(sp.getString("phone", ""));
            login_pwd.setText(sp.getString("pwdview", ""));

        }
        login_go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = login_phone.getText().toString();
                final String pwd = login_pwd.getText().toString();
                if (isMobileNO(phone)) {
                  //  openLoading();
                    login(phone, pwd);
                } else {
                    Toast.makeText(Login.this, "手机号格式错误！", Toast.LENGTH_LONG).show();

                }


            }
        });//登录按钮
        login_reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this, Register.class));

            }
        });//注册按钮
        login_forget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(Login.this, GetPwd.class));
            }
        });
    }



    public void onBackPressed() {
        //此处写退向后台的处理
        startActivity(new Intent(Login.this, Main.class));
        finish();

    }//手机返回键

    //    先先文件访问权限
    protected void judgePermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝

            // sd卡权限
            String[] SdCardPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (ContextCompat.checkSelfPermission(this, SdCardPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, SdCardPermission, 100);
            }

            String[] READ_EXTERNAL_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE};
            if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, READ_EXTERNAL_STORAGE, 500);
            }



        } else {
            //doSdCardResult();
        }


    }

    //正则表达验证手机号
    public static boolean isMobileNO(String mobiles) {
        String telRegex = "[1][3456789]\\d{9}";
        if (TextUtils.isEmpty(mobiles)) {
            return false;
        } else return mobiles.matches(telRegex);
    }

    //网络加载
    private void openLoading() {
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(Login.this)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }

    //关闭网络加载
    private void closeLoading() {
        shapeLoadingDialog.dismiss();
    }

    /**
     * 手机号码密码登录 (前提是手机号已经验证)
     */
    private void login(String phone, final String password) {
        /**查看手机号用户是否存在*/
        openLoading();
        BmobQuery<User> categoryBmobQuery = new BmobQuery<>();
        categoryBmobQuery.addWhereEqualTo("mobilePhoneNumber", phone);
        categoryBmobQuery.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null) {
                    if (object.size() > 0) {
                        Log.w("aaaa", "用户存在");
                        //TODO 此处替换为你的手机号码和密码
                        BmobUser.loginByAccount(phone, password, new LogInListener<User>() {
                            @Override
                            public void done(User user, BmobException e) {
                                if (user != null) {
                                    if (e == null) {

                                        Log.w("aaaa", "登录成功->ID:" + user.getObjectId() + "----用户名:" + user.getUsername());
                                        BmobFile bmobFile = user.getIcon();
                                        myData.setIconfileName(bmobFile.getFilename());
                                        myData.setUserName(user.getUsername());
                                        myData.setObjID(user.getObjectId());
                                        myData.setIconUrl(user.getIcon().getFileUrl());
                                        myData.setSex(user.getSex());
                                        myData.setBirth(user.getBirth());
                                        myData.setBirthPlace(user.getBirthPlace());
                                        myData.setEmail(user.getMyEamil());
                                        myData.setShow(user.getShow());
                                        //记住密码开始
                                        SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
                                        //获取editor
                                        SharedPreferences.Editor editor = sp.edit();
                                            //构造数据对
                                            editor.putString("phone", login_phone.getText().toString());
                                            editor.putString("pwd", login_pwd.getText().toString());
                                            editor.putString("pwdview", login_pwd.getText().toString());//登录页记住密码用
                                            editor.putBoolean("save", true);
                                            //提交数据
                                            editor.commit();
                                            //数据将保存到文件里

                                        Intent intent = new Intent(Login.this, Main.class);
                                        intent.putExtra("page", R.id.today_tab);//打开主页
                                        startActivity(intent);
                                        finish();

                                    } else {
                                        Log.w("aaaa", "登录失败：" + e.getErrorCode() + "-" + e.getMessage() + "\n");
                                        Toast.makeText(Login.this, "登录失败！", Toast.LENGTH_LONG).show();

                                    }
                                } else {
                                    Log.w("aaaa", "密码错误：" + e.getErrorCode() + "-" + e.getMessage() + "\n");
                                    Toast.makeText(Login.this, "密码错误！", Toast.LENGTH_LONG).show();

                                }
                            }
                        });
                    } else {
                        Log.w("aaaa", "用户不存在" + object.size());
                        Toast.makeText(Login.this, "用户不存在！", Toast.LENGTH_LONG).show();
                    }
                }
                closeLoading();
            }
        });
    }



}